package net.gyapp.markim.module.mine.account;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.easyder.wrapper.base.view.WrapperPickerActivity;
import com.easyder.wrapper.core.manager.ImageManager;
import com.easyder.wrapper.core.model.BaseVo;
import com.joooonho.SelectableRoundedImageView;
import com.luck.picture.lib.entity.LocalMedia;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.xuhao.android.libsocket.utils.Logger;

import net.gyapp.markim.ApiConfig;
import net.gyapp.markim.R;
import net.gyapp.markim.WrapperApplication;
import net.gyapp.markim.core.ImHelper;
import net.gyapp.markim.module.basic.base.CommonPresenter;
import net.gyapp.markim.module.basic.event.AccountChanged;
import net.gyapp.markim.module.basic.event.AccountIml;
import net.gyapp.markim.module.message.bean.QiniuTokenVo;
import net.gyapp.markim.module.mine.vo.MemberVo;
import net.gyapp.markim.utils.RequestParams;
import net.gyapp.markim.utils.libs.QiniuManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.winds.widget.usage.TitleView;

/**
 * Author:  winds
 * Data:    2018/7/7
 * Version: 1.0
 * Desc:
 */


public class PersonalInfoActivity extends WrapperPickerActivity<CommonPresenter> {

    @BindView(R.id.iv_header)
    SelectableRoundedImageView ivHeader;
    @BindView(R.id.tv_nick)
    TextView tvNick;
    @BindView(R.id.tv_social_account)
    TextView tvSocialAccount;
    private QiniuTokenVo avatarToken;

    public static Intent getIntent(Context context) {
        return new Intent(context, PersonalInfoActivity.class);
    }

    @Override
    protected int getViewLayout() {
        return R.layout.activity_personal_info;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setCenterText("个人资料");
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        getInfo();
    }

    @Override
    public void showContentView(String url, BaseVo dataVo) {
        if (url.contains(ApiConfig.API_GET_PICTURE_TOKEN)) {
            avatarToken = (QiniuTokenVo) dataVo;
            uploadImage();
        } else if (url.contains(ApiConfig.API_INFO)) {
            WrapperApplication.setMember((MemberVo) dataVo);
            fillMemberInfo();
        } else if (url.contains(ApiConfig.API_MODIFY_INFO)) {
            showToast("修改成功");
            EventBus.getDefault().post(new AccountChanged(AccountIml.ACCOUNT_AVATAR));
        }
    }

    private void fillMemberInfo() {
        if (WrapperApplication.isLogin()) {
            MemberVo member = WrapperApplication.getMember();
            ImageManager.load(mActivity, ivHeader, member.userInfo.userAvatar, R.drawable.placeholder_header);
            tvNick.setText(member.userInfo.nick);
        }
    }

    @Override
    public void obtainMediaResult(List<LocalMedia> list) {
        if (list != null && list.size() > 0) {
            path = list.get(0).getCutPath();
            upload(path);
        }
    }

    @Subscribe
    public void accountChanged(AccountChanged changed) {
        switch (changed.sign) {
            case AccountIml.ACCOUNT_NICK:
            case AccountIml.ACCOUNT_AVATAR:
                getInfo();
                break;
        }
    }

    @OnClick({R.id.iv_header, R.id.layout_set_nick, R.id.layout_qr_code, R.id.layout_social_account})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_header:
                showPictureSelector(1, true, true, true, false);
                break;
            case R.id.layout_set_nick:
                startActivity(ModifyTextActivity.getIntent(mActivity, "修改昵称", WrapperApplication.getMember().userInfo.nick, "昵称字符仅限中英文", -1, ModifyTextActivity.SIGN_MODIFY_NICK));
                break;
            case R.id.layout_qr_code:
                startActivity(VCardActivity.getIntent(mActivity));
                break;
            case R.id.layout_social_account:

                break;
        }
    }

    String path;

    private void uploadImage() {
        if (!TextUtils.isEmpty(path)) {
            upload(path);
        }
    }


    private void upload(String path) {
        if (avatarToken != null) {
            QiniuManager.getInstance().getUploadManager().put(path, null, avatarToken.uptoken, new UpCompletionHandler() {
                @Override
                public void complete(String key, ResponseInfo info, JSONObject response) {
                    if (info.isOK()) {
                        Logger.i("key " + key);
                        Logger.i("info " + info.toString());
                        Logger.i("response " + response.toString());

                        try {
                            changeAvatar(ImHelper.getActualPicturePath(response));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }, null);
        } else {
            getPictureToken();
        }
    }

    private void getPictureToken() {
        presenter.setNeedDialog(false);
        presenter.postData(ApiConfig.API_GET_PICTURE_TOKEN, QiniuTokenVo.class);
    }

    private void changeAvatar(String path) {
        presenter.postData(ApiConfig.API_MODIFY_INFO, new RequestParams().put("userAvatar", path).get(), BaseVo.class);
    }

    private void getInfo() {
        presenter.postData(ApiConfig.API_INFO, MemberVo.class);
    }


}
